package 数组.移除元素_快慢指针.删除重复项2;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/5/1 20:39
 * @description:给你一个有序数组 nums ，请你 原地 删除重复出现的元素，使得出现次数超过两次的元素只出现两次 ，返回删除后数组的新长度。
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums = {1,1,2,2,3};
        System.out.println(removeDuplicates(nums));
    }

    //快慢指针
    public static int removeDuplicates(int[] nums) {
        if (nums.length == 1) {
            return 1;
        }
        int mark = 1;
        int slow = 0;
        int fast = 1;
        while (fast <= nums.length - 1) {
            if (nums[fast] != nums[slow]) {
                slow++;
                nums[slow] = nums[fast];
                mark = 1;
            } else {
                if (mark < 2) {
                    mark++;
                    slow++;
                    nums[slow] = nums[fast];
                }
            }
            fast++;
        }
        return slow + 1;
    }

    //官方解法
    public static int removeDuplicates2(int[] nums) {
        int n = nums.length;
        if (n <= 2) {
            return n;
        }
        int slow = 2, fast = 2;
        while (fast < n) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}
